package com.sgb.packers.view.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;

import androidx.core.util.Pair;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ScreenUtils;
import com.sgb.packers.R;
import com.sgb.packers.databinding.PackersFragmentJobWorkEditBinding;
import com.sgb.packers.entity.ContractLaborEntity;
import com.sgb.packers.entity.WorkRecordsEntity;
import com.sgb.packers.view.activity.JobWorkEditActivity;
import com.sgb.packers.view.activity.PersonGetWorkActivity;
import com.sgb.packers.view.activity.ProjectManagerActivity;
import com.sgb.packers.view.adapter.ImageAdapter;
import com.sgb.packers.viewmodel.JobWorkEditFragViewModel;
import com.sgb.packers.widget.DayWorkPopWindow;
import com.sgb.packers.widget.SelectPopWindow;
import com.sgb.younghow.calendarview.Calendar;
import com.swgk.core.common.base.TeamBaseFragment;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.interfaces.DialogClick;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.MapUtils;
import com.swgk.core.util.NewDialogHelper;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.TransObjectUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.hutool.db.handler.StringHandler;

/**
 * @author : younghow
 * @date : 2021/11/18 11:21
 * description:个人记工-包工
 */
public class JobWorkEditFragment extends TeamBaseFragment<JobWorkEditFragViewModel, PackersFragmentJobWorkEditBinding> implements ItemInputTextView.OnWholeItemClickListener {

    private String projectName;
    private String projectNo;
    private String no;
    private List<Calendar> mSelectCalendar;
    private DayWorkPopWindow workTakePopWindow;
    private SelectPopWindow selectPopWindow;
    private String quantitiesUnit = "1";
    private String picture;
    private ImageAdapter mPicAdapter;
    private List<File> fileList;
    private List<String> mUploadImgList;
    private List<PickSelectEntity> projectUnitEntityList;
    private PersonGetWorkActivity personGetWorkActivity;
    private JobWorkEditActivity jobWorkEditActivity;
    private String unitName;

    public static JobWorkEditFragment newInstance(String projectName, int year, int month, int day, String projectNo) {
        JobWorkEditFragment pointWorkEditFragment = new JobWorkEditFragment();
        Bundle bundle = new Bundle();
        bundle.putString("projectName", projectName);
        bundle.putInt("year", year);
        bundle.putInt("month", month);
        bundle.putInt("day", day);
        bundle.putString("projectNo", projectNo);
        pointWorkEditFragment.setArguments(bundle);
        return pointWorkEditFragment;
    }

    public static JobWorkEditFragment newInstance(String projectName, int year, int month, int day, String projectNo, String no) {
        JobWorkEditFragment pointWorkEditFragment = new JobWorkEditFragment();
        Bundle bundle = new Bundle();
        bundle.putString("projectName", projectName);
        bundle.putInt("year", year);
        bundle.putInt("month", month);
        bundle.putInt("day", day);
        bundle.putString("projectNo", projectNo);
        bundle.putString("no", no);
        pointWorkEditFragment.setArguments(bundle);
        return pointWorkEditFragment;
    }

    @Override
    protected Class<JobWorkEditFragViewModel> createVM() {
        return JobWorkEditFragViewModel.class;
    }

    @Override
    protected void initView() {
        GridLayoutManager manager = new GridLayoutManager(getContext(), 4);
        mBinding.rvPhoto.setLayoutManager(manager);
        mPicAdapter = new ImageAdapter(getContext(), new ArrayList<>(), new ArrayList<>(), 5);
        mBinding.rvPhoto.setHasFixedSize(false);
        mBinding.rvPhoto.addItemDecoration(new GridSpacingItemDecoration(3, ScreenUtils.dip2px(getContext(), 2), false));
        mBinding.rvPhoto.setAdapter(mPicAdapter);
        mPicAdapter.setOpenListener(new ImageAdapter.OpenListener() {
            @Override
            public void onOpen() {
                if (personGetWorkActivity != null) {
                    personGetWorkActivity.setType(2);
                }
            }
        });

        mBinding.tvWorkHourNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(mBinding.tvUnitPrice.getText().toString()) && !TextUtils.isEmpty(mBinding.tvWorkHourNumber.getText().toString())) {
                    mBinding.tvTodaySalary.setText(String.format(Locale.CHINA, "%.2f", Double.parseDouble(mBinding.tvUnitPrice.getText().toString()) * Double.parseDouble(mBinding.tvWorkHourNumber.getText().toString())));
                } else {
                    mBinding.tvTodaySalary.setText("");
                }
            }
        });


        mBinding.tvUnitPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();
                if (s.contains(".")) {
                    mBinding.tvUnitPrice.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6 + 2 + 1)});
                    if (s.length() - 1 - s.indexOf(".") > 2) {
                        s = s.substring(0, s.indexOf(".") + 2 + 1);
                        editable.replace(0, editable.length(), s.trim());
                    }
                } else {
                    mBinding.tvUnitPrice.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6 + 1)});
                    if (s.length() > 6) {
                        s = s.substring(0, 6);
                        editable.replace(0, editable.length(), s.trim());
                    }

                }
                if (".".equals(s.trim())) {
                    s = "0" + s;
                    editable.replace(0, editable.length(), s.trim());
                }

                if (s.startsWith("0") && s.trim().length() > 1) {
                    if (s.charAt(1) != '.') {
                        editable.replace(0, editable.length(), "0");
                    }
                }

                if (!TextUtils.isEmpty(mBinding.tvWorkHourNumber.getText().toString()) && !TextUtils.isEmpty(mBinding.tvUnitPrice.getText().toString())) {
                    mBinding.tvTodaySalary.setText(String.format(Locale.CHINA, "%.2f", Double.parseDouble(mBinding.tvUnitPrice.getText().toString()) * Double.parseDouble(mBinding.tvWorkHourNumber.getText().toString())));
                } else {
                    mBinding.tvTodaySalary.setText("");
                }
            }
        });

        mBinding.etRemarks.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mBinding.tvRemarksWordsNumber.setText(String.format(Locale.CHINA, "%d/%d", mBinding.etRemarks.getText().toString().length(), 300));
            }
        });
    }

    private void initLiveData() {
        if (TextUtils.isEmpty(no)) {
            personGetWorkActivity = (PersonGetWorkActivity) getActivity();
            if (personGetWorkActivity != null) {
                personGetWorkActivity.mPictureLiveData.observe(getViewLifecycleOwner(), intent -> {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(intent);
                    fileList.clear();
                    mUploadImgList.clear();
                    for (LocalMedia localMedia : selectList) {
                        File file = new File(localMedia.getRealPath());
                        fileList.add(file);
                        mUploadImgList.add(localMedia.getRealPath());
                    }
                    mPicAdapter.setDatas(selectList, mUploadImgList);
                    mPicAdapter.setFileList(fileList);
                });
            }
        }else {
           jobWorkEditActivity = (JobWorkEditActivity) getActivity();
           if (jobWorkEditActivity != null){
               jobWorkEditActivity.mIntentLiveData.observe(getViewLifecycleOwner(), intent -> {
                   List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(intent);
                   fileList.clear();
                   mUploadImgList.clear();
                   for (LocalMedia localMedia : selectList) {
                       File file = new File(localMedia.getRealPath());
                       fileList.add(file);
                       mUploadImgList.add(localMedia.getRealPath());
                   }
                   mPicAdapter.setDatas(selectList, mUploadImgList);
                   mPicAdapter.setFileList(fileList);
               });
           }
        }

        mViewModel.uploadUrls.observe(getViewLifecycleOwner(), strings -> {
            StringBuilder stringBuilder = new StringBuilder();
            for (String string : strings) {
                stringBuilder.append(",").append(string);
            }
            stringBuilder.delete(0, 1);
            picture = stringBuilder.toString();

            upload();
        });

        mViewModel.uploadSuccess.observe(getViewLifecycleOwner(), aBoolean -> {
            if (aBoolean) {
                getActivity().finish();
            }
        });

        mViewModel.projectUnitEntity.observe(getViewLifecycleOwner(), projectUnitEntities -> {
            this.projectUnitEntityList = projectUnitEntities;
        });

        mViewModel.jobWorkDetail.observe(getViewLifecycleOwner(), new Observer<ContractLaborEntity>() {
            @Override
            public void onChanged(ContractLaborEntity contractLaborEntity) {
                try {
                    TransObjectUtils.transObject(contractLaborEntity);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

                if (contractLaborEntity.quantities > 0){
                    mBinding.tvWorkHourNumber.setText(String.format(Locale.CHINA, "%.2f", contractLaborEntity.quantities));
                }else {
                    mBinding.tvWorkHourNumber.setText("");
                }

                mBinding.tvUnitPrice.setText(contractLaborEntity.unitPrice);
                mBinding.tvTodaySalary.setText(contractLaborEntity.salary);
                mBinding.etRemarks.setText(contractLaborEntity.remark);
                if (!TextUtils.isEmpty(contractLaborEntity.picture)){
                    String[] pictures = contractLaborEntity.picture.split(",");
                    List<String> list = new ArrayList<>(Arrays.asList(pictures));
                    mPicAdapter.setNetImgList(list);
                }

                picture = contractLaborEntity.picture;
                quantitiesUnit = contractLaborEntity.quantitiesUnit;
                projectNo = contractLaborEntity.projectNo;
                projectName = contractLaborEntity.projectName;
                no = contractLaborEntity.no;

                switch (contractLaborEntity.quantitiesUnit) {
                    case "2":
                        mBinding.tvSalaryStandard.setText("立方米");
                        break;
                    case "3":
                        mBinding.tvSalaryStandard.setText("吨");
                        break;
                    case "4":
                        mBinding.tvSalaryStandard.setText("米");
                        break;
                    case "5":
                        mBinding.tvSalaryStandard.setText("寸");
                        break;
                    case "6":
                        mBinding.tvSalaryStandard.setText("个");
                        break;
                    case "7":
                        mBinding.tvSalaryStandard.setText("次");
                        break;
                    case "8":
                        mBinding.tvSalaryStandard.setText("天");
                        break;
                    case "9":
                        mBinding.tvSalaryStandard.setText("块");
                        break;
                    case "10":
                        mBinding.tvSalaryStandard.setText("组");
                        break;
                    case "11":
                        mBinding.tvSalaryStandard.setText("台");
                        break;
                    case "12":
                        mBinding.tvSalaryStandard.setText("捆");
                        break;
                    case "13":
                        mBinding.tvSalaryStandard.setText("宗");
                        break;
                    case "14":
                        mBinding.tvSalaryStandard.setText("项");
                        break;
                    case "15":
                        mBinding.tvSalaryStandard.setText("珠");
                        break;
                    case "1":
                    default:
                        mBinding.tvSalaryStandard.setText("平方米");
                        break;
                }

                unitName = mBinding.tvSalaryStandard.getText().toString();
            }
        });

        mViewModel.delJobWork.observe(getViewLifecycleOwner(), aBoolean -> getActivity().finish());
    }

    @Override
    protected void initData() {
        mSelectCalendar = new ArrayList<>();
        mUploadImgList = new ArrayList<>();
        fileList = new ArrayList<>();
        if (getArguments() != null) {
            projectName = getArguments().getString("projectName");
            projectNo = getArguments().getString("projectNo");
            no = getArguments().getString("no");

            if (!TextUtils.isEmpty(no)) {
                mBinding.llChangeDelete.setVisibility(View.VISIBLE);
                mBinding.tvUpload.setVisibility(View.GONE);
            } else {
                mBinding.llChangeDelete.setVisibility(View.GONE);
                mBinding.tvUpload.setVisibility(View.VISIBLE);
            }
            mBinding.tvFragmentTradePublishSelectType.setText(projectName);
            int year;
            int month;
            int day;
            if (getArguments().getInt("year") != 0) {
                year = getArguments().getInt("year");
                month = getArguments().getInt("month");
                day = getArguments().getInt("day");
                Calendar calendar = new Calendar();
                calendar.setCurrentDay(true);
                calendar.setCurrentMonth(true);
                calendar.setDay(day);
                calendar.setMonth(month);
                calendar.setYear(year);
                mSelectCalendar.add(calendar);
            } else {
                String[] date = DateUtils.timestamp2DateNumber(System.currentTimeMillis());
                Calendar calendar = new Calendar();
                calendar.setCurrentDay(true);
                calendar.setCurrentMonth(true);
                calendar.setDay(Integer.parseInt(date[2]));
                calendar.setMonth(Integer.parseInt(date[1]));
                calendar.setYear(Integer.parseInt(date[0]));
                mSelectCalendar.add(calendar);
                day = Integer.parseInt(date[2]);
                month = Integer.parseInt(date[1]);
                year = Integer.parseInt(date[0]);
            }

            mBinding.iitSelectDate.setContent(String.format(Locale.CHINA, "%s年%s月%s日", year, month, day));
        }
        mViewModel.getProjectUnit();

        if (!TextUtils.isEmpty(no)) {
            mViewModel.wrapWorkDetail(no, "1");
        }

        initLiveData();
        initListener();
    }

    private void initListener() {
        if (TextUtils.isEmpty(no)) {
            mBinding.iitSelectDate.setOnWholeItemClickListener(this);
        }
        mBinding.tvSalaryStandard.setOnClickListener(this);
        mBinding.tvUpload.setOnClickListener(this);
        mBinding.tvDelete.setOnClickListener(this);
        mBinding.tvSaveChange.setOnClickListener(this);
    }

    @Override
    protected int layoutId() {
        return R.layout.packers_fragment_job_work_edit;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == R.id.tv_salary_standard) {
            if (selectPopWindow == null) {
                selectPopWindow = new SelectPopWindow(getContext());
                selectPopWindow.setDialogClick(new DialogClick<PickSelectEntity>() {
                    @Override
                    public void confirmClickData(PickSelectEntity pickSelectEntity) {
                        mBinding.tvSalaryStandard.setText(pickSelectEntity.getProjectscale());
                        quantitiesUnit = pickSelectEntity.getNo();
                        unitName = "";
                    }
                });
                selectPopWindow.setData(projectUnitEntityList);
            }

            if (!TextUtils.isEmpty(unitName)){
                int position = 0;
                for (int i = 0; i < projectUnitEntityList.size(); i++) {
                    if (projectUnitEntityList.get(i).getProjectscale().equals(unitName)){
                        position = i;
                    }
                }
                selectPopWindow.setDefaultUnit(position);
            }
            selectPopWindow.showPopwindow(mBinding.etRemarks, Gravity.BOTTOM, 0, 0);
        } else if (id == R.id.tv_upload) {
            if (TextUtils.isEmpty(mBinding.tvTodaySalary.getText().toString())) {
                MToast.showToast(getContext(), "请输入当日工资");
                return;
            }

            List<File> file = mPicAdapter.getFileList();
            if (file.size() > 0) {
                mViewModel.uploadFile(file);
            } else {
                upload();
            }
        } else if (id == R.id.tv_delete) {
            RoundCornerDialog cornerDialog = new NewDialogHelper<String>(getContext(), R.layout.library_dialog_salary_sure_no_title)
                    .text(R.id.tv_message, "确认删除该记工")
                    .text(R.id.tv_logout_cancel, "取消")
                    .text(R.id.tv_logout_confirm, "确定")
                    .onClick(R.id.tv_logout_confirm, new DialogClick<String>() {
                        @Override
                        public void confirmClick(String s, Dialog dialog) {
                            mViewModel.delJobWork(no);
                            dialog.dismiss();
                        }
                    })
                    .onClick(R.id.tv_logout_cancel, new DialogClick<String>() {
                        @Override
                        public void confirmClick(String s, Dialog dialog) {
                            dialog.dismiss();
                        }
                    })
                    .build();
            cornerDialog.show();
        } else if (id == R.id.tv_save_change) {
            if (TextUtils.isEmpty(mBinding.tvTodaySalary.getText().toString())) {
                MToast.showToast(getContext(), "请输入当日工资");
                return;
            }

            List<File> file = mPicAdapter.getFileList();
            if (file.size() > 0) {
                mViewModel.uploadFile(file);
            } else {
                upload();
            }
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        if (view.getId() == R.id.iit_select_date) {
            if (workTakePopWindow == null) {
                workTakePopWindow = new DayWorkPopWindow(getContext());
                Calendar[] selectCalendar = new Calendar[mSelectCalendar.size()];
                for (int i = 0; i < mSelectCalendar.size(); i++) {
                    selectCalendar[i] = mSelectCalendar.get(i);
                }

                workTakePopWindow.setDefaultCalendar(selectCalendar);
                workTakePopWindow.setSelectYearMonth();
                workTakePopWindow.setSelect(selectCalendar);
                workTakePopWindow.setTransCalender(list -> {
                    mSelectCalendar = list;
                    if (list != null && list.size() > 0) {
                        if (list.size() == 1) {
                            mBinding.iitSelectDate.setContent(String.format(Locale.CHINA, "%d年%d月%d日", list.get(0).getYear(), list.get(0).getMonth(), list.get(0).getDay()));
                        } else {
                            mBinding.iitSelectDate.setContent(String.format(Locale.CHINA, "选择%d天", list.size()));
                        }
                        workTakePopWindow.dismiss();
                    } else {
                        MToast.showToast(getContext(), "请选择日期");
                    }
                });
            }

            workTakePopWindow.showPopwindow(mBinding.iitSelectDate, Gravity.BOTTOM, 0, 0);
        }
    }

    private void upload() {
        StringBuilder stringBuilder = new StringBuilder();
        for (Calendar calendar : mSelectCalendar) {
            stringBuilder.append(",").append(calendar.getYear()).append("-").append(calendar.getMonth()).append("-").append(calendar.getDay());
        }

        stringBuilder.delete(0, 1);

        Map<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(mBinding.tvWorkHourNumber.getText().toString())) {
            map.put("quantities", Double.valueOf(mBinding.tvWorkHourNumber.getText().toString()));
        }
        if (!TextUtils.isEmpty(no)) {
            map.put("no", no);
        }
        map.put("picture", picture);
        map.put("projectName", projectName);
        map.put("projectNo", projectNo);
        map.put("recordType", 1);
        map.put("remark", mBinding.etRemarks.getText().toString());
        if (!TextUtils.isEmpty(mBinding.tvTodaySalary.getText().toString())) {
            map.put("salary", Double.valueOf(mBinding.tvTodaySalary.getText().toString()));
        }
        map.put("quantitiesUnit", quantitiesUnit);
        if (!TextUtils.isEmpty(mBinding.tvUnitPrice.getText().toString())) {
            map.put("unitPrice", Double.valueOf(mBinding.tvUnitPrice.getText().toString()));
        }
        map.put("userNo", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO, ""));
        map.put("workTime", mSelectCalendar.get(0).getTimeInMillis());
        mViewModel.uploadWork(map);
    }
}
